public class Solution {
    public int rob(int[] nums) {
        int len = nums.length;

        if (len == 0) {
            return 0;
        } else if (len == 1) {
            return nums[0];
        } else if (len == 2) {
            return Math.max(nums[0], nums[1]);
        } else if (len == 3) {
            return Math.max(Math.max(nums[0], nums[1]), nums[2]);
        }

        //第一位选
        int[] f1 = new int[len];
        int[] g1 = new int[len];

        //初始化
        f1[2] = nums[0] + nums[2];
        g1[2] = nums[0];

        for (int i = 3; i < len - 1; i++) {//最后一位不选
            f1[i] = g1[i - 1] + nums[i];
            g1[i] = Math.max(f1[i - 1], g1[i - 1]);
        }

        int ret1 = ret1 = Math.max(f1[len - 2], g1[len - 2]);;

        //第一位不选
        int[] f2 = new int[len];
        int[] g2 = new int[len];

        f2[1] = nums[1];

        for (int i = 2; i < len; i++) {
            f2[i] = g2[i - 1] + nums[i];
            g2[i] = Math.max(f2[i - 1], g2[i - 1]);
        }

        int ret2 = Math.max(f2[len - 1], g2[len - 1]);

        return Math.max(ret1, ret2);
    }

    public int rob2(int[] nums) {
        int len = nums.length;

        //左边为第一位选，右边为第一位不选
        return Math.max(nums[0] + subRob(nums, 2, len - 2), subRob(nums, 1, len - 1));
    }

    private int subRob(int[] nums, int left, int right) {
        if (left > right) {
            return 0;
        }

        int len = nums.length;

        int[] f = new int[len];
        int[] g = new int[len];

        f[left] = nums[left];

        for (int i = left + 1; i <= right; i++) {
            f[i] = g[i - 1] + nums[i];
            g[i] = Math.max(g[i - 1], f[i - 1]);
        }

        return Math.max(f[right], g[right]);
    }
}
